package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.impl.DishServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saves (dishDto);
        /*清理某个分类下菜品的缓存数据*/
        String key ="dish_"+dishDto.getCategoryId ()+"_1";
        redisTemplate.delete (key);
        return R.success ("新增成功");
    }
    //分页查询
    @GetMapping("/page")
    //分页查询
    //菜品表的分页构造-》拷贝到dto的分页构造器（除了page下的records）-》
    // 获得dish的records拷贝到dto-》获得分类id-》id查询分类对象-》分类对象存入dto的records
    public R<IPage> pages(int page, int pageSize, String name){
        /*//构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<> ();
        //添加过滤条件
        qw.like(name != null,Dish::getName,name);
        //添加排序条件
        qw.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,qw);

        //对象拷贝
        //pageInfo里面的值拷贝到dishDtoPage，在返回，除了records不拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);*/
       return dishService.findByPage (page,pageSize,name);
    }
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }
    @GetMapping("/list")
    //根据条件查询分类数据
    //新增菜品的下拉列表
    public R<List<DishDto>> list(Dish dish){
       /* LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<> ();
        qw.eq (dish.getCategoryId ()!=null,Dish::getCategoryId,dish.getCategoryId ());
        //添加条件，查询状态为1（起售状态）的菜品
        qw.eq(Dish::getStatus,1);
        qw.orderByAsc (Dish::getSort).orderByDesc (Dish::getUpdateTime);
        List<Dish> dishes=dishMapper.selectList (qw);
        return R.success (dishes);*/

        List<DishDto> dishList=null;
       //动态构造key
      String key="dish_"+dish.getCategoryId ()+"_"+dish.getStatus ();
        //获取缓存数据
        dishList=(List<DishDto>) redisTemplate.opsForValue ().get (key);
        if(dishList!=null){
            //存在，直接返回，不要查询数据库
            return R.success (dishList);
        }
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<> ();
        qw.eq (dish.getCategoryId ()!=null,Dish::getCategoryId,dish.getCategoryId ());
        //添加条件，查询状态为1（起售状态）的菜品
        qw.eq(Dish::getStatus,1);
        qw.orderByAsc (Dish::getSort).orderByDesc (Dish::getUpdateTime);
        List<Dish> list=dishService.list (qw);
        dishList=list.stream ().map ((item)->{

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品id
            Long dishid=item.getId ();
            LambdaQueryWrapper<DishFlavor> qw1=new LambdaQueryWrapper<> ();
            qw1.eq (DishFlavor::getDishId,dishid);
            List<DishFlavor> list1=dishFlavorService.list (qw1);
            dishDto.setFlavors (list1);

            return dishDto;
        }).collect(Collectors.toList());
        //不存在，就将菜品数据缓存到redis
        redisTemplate.opsForValue ().set (key,dishList,60, TimeUnit.MINUTES);
        return R.success (dishList);
      //return dishService.list (dish);
    }

    @DeleteMapping
    public R<String> deletes(@RequestParam List<Long> ids){
        dishService.remove (ids);
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys);
        return R.success ("删除成功");
    }
    //售卖状态
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<> ();
        qw.in(Dish::getId,ids);
        List<Dish> list=dishService.list (qw);
        for (Dish dish : list) {
            if(dish!=null){
                dish.setStatus (status);
                dishService.updateById (dish);
            }
        }
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys);
        return R.success ("状态修改成功");
    }
}
